﻿using AwesomiumDotNet;
using System;
using System.Drawing;
using System.Threading;

namespace BitmapSample
{
    class BitmapSample
    {
        int Width = 640;
        int Height = 480;
        string URL = "http://www.google.com";

        bool isRunning = true;
        WebView webView;

        public BitmapSample()
        {
            WebCoreConfig config = new WebCoreConfig();
            config.SetLogLevel(LogLevel.None);
            //config.SetEnablePlugins(true);
            WebCore webCore = new WebCore(config);

            webView = webCore.CreateWebView(Width, Height);
            webView.BeginNavigation += OnBeginNavigation;
            webView.FinishLoading += OnFinishLoading;
            
            webView.LoadUrl(URL);
            //webView.LoadFile("index.html");
            
            while (isRunning)
            {
                Thread.Sleep(250);
                webCore.Update();
            }
            
            System.Console.WriteLine("Done.\n");

            webView.Dispose();
            webCore.Dispose();
        }

        private void OnBeginNavigation(object sender, BeginNavigationEventArgs e)
        {
            System.Console.WriteLine("Navigating to " + e.Url);
        }

        private void OnFinishLoading(object sender, FinishLoadingEventArgs e)
        {
            System.Console.WriteLine("Rendering...");

            RenderBuffer buffer = webView.Render();

            // Write to BMP file
            using (Bitmap bitmap = buffer.ToBitmap(Width*3, 3))
                bitmap.Save("result.bmp");

            isRunning = false;
        }
    }
}
